package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.WrokRequestList.WorkRequestDetail;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 办公申请详情
 *
 * @author wu
 */
public class WorkRequestDetailFragment extends WorkRequestBaseFragment {

  public static final String EXTRA_VALUE = "com.isunland.managesystem.ui.EXTRA_VALUE";
  private WorkRequestDetail mDetail;
  private String mId;
  private String mRegisterTime;// 登记时间
  private String mDataStatus;// 数据状态
  protected CurrentUser mCurrentUser;
  private String mLoginJobNum;
  private String mRunId;
  private String mRegisterId;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 设置返回图标
    setBack(true);
    setTitleCustom(R.string.workReusestDetail);
    mCurrentUser = CurrentUser.newInstance(getActivity());
    mLoginJobNum = mCurrentUser.getJobNumber();
    mDetail = (WorkRequestDetail) getArguments().getSerializable(EXTRA_VALUE);
    if (mDetail != null) {
      mId = mDetail.getId();
      mRequestIntroduction = mDetail.getCooperateDetails();
      mCorporator = mDetail.getCooperateManName();
      mRegistjobNos = mDetail.getCooperateManId();
      mRequestFnishTime = mDetail.getFinishTime();
      mRegister = mDetail.getRegStaffName();
      mRegisterId = mDetail.getRegStaffId();
      mRegisterTime = mDetail.getRegDate();
      mDataStatus = mDetail.getDataStatus();
      mRunId = mDetail.getRunId();
    }

  }

  protected void initView() {
    if (!TextUtils.isEmpty(mRequestIntroduction)) {
      mRequestIntroduction_workRequest.setText(mRequestIntroduction);
    }
    if (!TextUtils.isEmpty(mRequestFnishTime)) {
      mCompleteTime_workRequest.setText(mRequestFnishTime);
    }
    if (!TextUtils.isEmpty(mCorporator)) {
      mCorporator_WorkRequest.setText(mCorporator);
    }
    if (!TextUtils.isEmpty(mRegister)) {
      mRegister_workRequest.setText(mRegister);
    }
    if (!TextUtils.isEmpty(mRegisterTime)) {
      mRegisterTime_workRequest.setText(mRegisterTime);
    }

    if (!TextUtils.isEmpty(mDataStatus)) {
      if ("new".equalsIgnoreCase(mDataStatus)) {
        mDataStatus_workRequest.setText(getString(R.string.draft));
      } else if ("waitCheck".equalsIgnoreCase(mDataStatus)) {
        mDataStatus_workRequest.setText(R.string.checking);
      } else if ("checkPass".equalsIgnoreCase(mDataStatus)) {
        mDataStatus_workRequest.setText(R.string.checkapprovve);
      } else if ("abort".equalsIgnoreCase(mDataStatus)) {
        mDataStatus_workRequest.setText(R.string.stopup);
      }
    }

    if ("checkPass".equalsIgnoreCase(mDataStatus) || "waitCheck".equalsIgnoreCase(mDataStatus)) {
      mRequestIntroduction_workRequest.setEnabled(false);
      mCompleteTime_workRequest.setEnabled(false);
      mCorporator_WorkRequest.setEnabled(false);
    }
  }

  @Override // 响应返回图标
  public boolean onOptionsItemSelected(MenuItem item) {
    AlertDialog.Builder dialog;
    switch (item.getItemId()) {

      case android.R.id.home:
        getActivity().finish();
        break;

      case R.id.menu_item_save:
        if (!mLoginJobNum.equalsIgnoreCase(mRegisterId)) {
          ToastUtil.show(R.string.onlyCreaterEdit);
        } else {
          if (TextUtils.isEmpty(mRequestIntroduction_workRequest.getText().toString().trim())) {
            ToastUtil.show(R.string.completerequestConstruction);
          } else if (MyUtils.isEmptyText(mCompleteTime_workRequest)) {
            ToastUtil.show(R.string.completeMusttimeWorkRequest);
          } else if (MyUtils.isEmptyText(mCorporator_WorkRequest)) {
            ToastUtil.show(R.string.mustCorporator);
          } else {
            dialog = new AlertDialog.Builder(getActivity());
            dialog.setTitle(R.string.restart_title);
            dialog.setMessage(R.string.ifSave);
            dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

              @Override public void onClick(DialogInterface dialog, int which) {
                volleyPostSave();
              }
            });

            dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

              @Override public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
              }
            });
            dialog.create().show();
          }
        }
        break;
      case R.id.menu_item_submit:
        if (!mLoginJobNum.equalsIgnoreCase(mRegisterId)) {
          ToastUtil.show(R.string.onluCreaterStart);
        } else {
          if (TextUtils.isEmpty(mRequestIntroduction_workRequest.getText().toString().trim())) {
            ToastUtil.show(R.string.completerequestConstruction);
          } else if (MyUtils.isEmptyText(mCompleteTime_workRequest)) {
            ToastUtil.show(R.string.completeMusttimeWorkRequest);
          } else if (MyUtils.isEmptyText(mCorporator_WorkRequest)) {
            ToastUtil.show(R.string.mustCorporator);
          } else {
            dialog = new AlertDialog.Builder(getActivity());
            dialog.setTitle(R.string.restart_title);
            dialog.setMessage(R.string.ifSureStart);
            dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

              @Override public void onClick(DialogInterface dialog, int which) {
                volleyPostSubmit();
              }
            });

            dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

              @Override public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
              }
            });
            dialog.create().show();
          }
        }
        break;
      case R.id.menu_item_delete:
        if (!mLoginJobNum.equalsIgnoreCase(mRegisterId)) {
          ToastUtil.show(R.string.onluCreaterDelete);
        } else {
          dialog = new AlertDialog.Builder(getActivity());
          dialog.setTitle(R.string.restart_title);
          dialog.setMessage(R.string.deleteMind);
          dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              volleyPostDelete();
            }
          });

          dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
            }
          });
          dialog.create().show();
        }
        break;

      case R.id.menu_item_stop:
        if (!mLoginJobNum.equalsIgnoreCase(mRegisterId)) {
          ToastUtil.show(R.string.onluCreaterStop);
        } else {
          dialog = new AlertDialog.Builder(getActivity());
          dialog.setTitle(R.string.restart_title);
          dialog.setMessage(R.string.ifSureStop);
          dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              volleyPostStop();
            }
          });

          dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override public void onClick(DialogInterface dialog, int which) {
              dialog.dismiss();
            }
          });
          dialog.create().show();
        }
        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  /**
   * 终止流程
   */
  private void volleyPostStop() {
    MyUtils.showDialogLoading(getActivity(), R.string.interrupting);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TASK_STOP);
    HashMap<String, String> params = new HashMap<>();
    if (mRunId != null && !("".equalsIgnoreCase(mRunId))) {
      params.put("runId", mRunId);

      mActivity.volleyPost(url, params, new VolleyResponse() {

        @Override public void onVolleyResponse(String arg0) throws JSONException {
          MyUtils.dismissDialog();
          try {

            SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);
            String successType = successsMessage.getResult();
            if (successType.equals("1")) {
              ToastUtil.show(R.string.interruptSuccess);
              MyUtils.dismissDialog();
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
            } else {
              MyUtils.show(getActivity(), R.string.interruptFail);
            }
          } catch (Exception e) {
            LogUtil.e("interruptError", e);
            MyUtils.show(getActivity(), R.string.interruptFail);
          }
        }

        @Override public void onVolleyError(VolleyError arg0) {
          LogUtil.e("VolleyError", arg0);
          ToastUtil.show(R.string.failure_operation);
        }
      });
    }
  }

  /**
   * 删除
   */
  private void volleyPostDelete() {
    MyUtils.showDialogLoading(getActivity(), R.string.deleting);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELITE_EORKREQUEST);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
        String resutl = success.getResult();
        String message = success.getMessage();
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(resutl)) {
          ToastUtil.show(message);
          MyUtils.dismissDialog();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }

        if (SuccessMessage.FAILURE.equalsIgnoreCase(resutl)) {
          MyUtils.show(getActivity(), message);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.show(getActivity(), R.string.deleteFail);
        LogUtil.e("arg0===" + arg0);
      }
    });
  }

  /**
   * 启动流程
   */
  private void volleyPostSubmit() {
    MyUtils.showDialogLoading(getActivity(), R.string.loadingStart);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_START_WORKREQUEST);
    HashMap<String, String> params = getparams();
    params.put("dataStatus", "waitCheck");
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          SuccessMessage message = new Gson().fromJson(arg0, SuccessMessage.class);
          String result = message.getResult();
          String messages = message.getMessage();
          if (SuccessMessage.SUCCESS.equalsIgnoreCase(result)) {
            ToastUtil.show(R.string.startFolwSuccess);
            MyUtils.dismissDialog();
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else {
            ToastUtil.show(messages);
          }
        } catch (Exception e) {
          MyUtils.show(getActivity(), R.string.startFolwFail);
          LogUtil.e("startError", e);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.startFolwFail);
      }
    });
  }

  /**
   * 保存
   */
  private void volleyPostSave() {
    MyUtils.showDialogLoading(getActivity(), R.string.loadingSave);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_SAVE_WORKREQUEST);
    HashMap<String, String> params = getparams();
    params.put("dataStatus", mDataStatus);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
        String resutl = success.getResult();
        if (SuccessMessage.SUCCESS.equalsIgnoreCase(resutl)) {
          MyUtils.show(getActivity(), R.string.save_success);
          MyUtils.dismissDialog();
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }

        if (SuccessMessage.FAILURE.equalsIgnoreCase(resutl)) {
          MyUtils.show(getActivity(), R.string.save_failure);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.save_failure);
      }
    });

    LogUtil.i("saveparams=====" + params);
  }

  private HashMap<String, String> getparams() {
    HashMap<String, String> params = new HashMap<>();

    String introduction = mRequestIntroduction_workRequest.getText().toString().trim();
    String completeTime = mCompleteTime_workRequest.getText().toString().trim();
    String corporator = mCorporator_WorkRequest.getText().toString().trim();
    String register = mRegister_workRequest.getText().toString().trim();
    String registTime = mRegisterTime_workRequest.getText().toString().trim();
    String dataStatus = mDataStatus_workRequest.getText().toString().trim();

    params.put("id", mId);
    params.put("cooperateDetails", introduction);
    params.put("finishTime", completeTime);
    params.put("cooperateManName", corporator);
    params.put("cooperateManId", mRegistjobNos);
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("memberName", mCurrentUser.getMemberName());
    return params;
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    if ("new".equalsIgnoreCase(mDataStatus) || "abort".equalsIgnoreCase(mDataStatus)) {
      inflater.inflate(R.menu.menu_save_submit_delete, menu);
    } else if ("waitCheck".equalsIgnoreCase(mDataStatus)) {
      inflater.inflate(R.menu.menu_stop, menu);
    } else {
    }
    super.onCreateOptionsMenu(menu, inflater);
  }

  public static Fragment newInstance(WorkRequestDetail detail) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_VALUE, detail);
    WorkRequestDetailFragment fragment = new WorkRequestDetailFragment();
    fragment.setArguments(bundle);
    return fragment;
  }
}
